package com.dlc.shop.live.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.dlc.shop.common.bean.AliLive;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.live.common.constant.PlayBackType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Objects;

/**
 * 阿里云直播工具
 * @author TRACK
 */
public class AliLiveUtil {
    private static final Logger logger = LoggerFactory.getLogger(AliLiveUtil.class);

    /**
     * 根据流名称创建推流url
     * @param streamName 视频直播根据流名称（StreamName）而不是根据应用名称（AppName）来判断直播流是否唯一
     * @param endTime 直播间结束时间
     * @param aliLive 阿里云直播配置
     * @return 推流域名+AppName（应用）+StreamName（直播流）+鉴权串
     */
    public static String getPushUrl(String streamName, Date endTime, AliLive aliLive) {
        if (Objects.isNull(streamName) || StrUtil.isBlank(streamName)) {
            throw new YamiShopBindException("Stream name cannot be null");
        }
        // 推流域名
        String pushDomain = aliLive.getPushDomain();
        // 应用名称
        String appName = aliLive.getAppName();
        // 推流鉴权key
        String pushAuthKey = aliLive.getPushAuthKey();
        // 过期时间
        String exp = String.valueOf(endTime.getTime() / 1000);
        // 推流前缀：rtmp://{pushDomain}/{appName}/{streamName}
        String pushPrefixUrl = StrUtil.format("rtmp://{}/{}/{}", pushDomain, appName, streamName);

        // 组合md5加密串 /{appName}/{streamName}-{exp}-0-0-{pushAuthKey}
        String md5Url = StrUtil.format("/{}/{}-{}-0-0-{}", appName, streamName, exp, pushAuthKey);
        // md5加密
        String md5Hex = DigestUtil.md5Hex(md5Url);
        // 推流路径 {pushPrefixUrl}?auth_key={exp}-0-0-{md5Hex}
        String pushUrl = StrUtil.format("{}?auth_key={}-0-0-{}", pushPrefixUrl, exp, md5Hex);
        logger.info("推流路径为：" + pushUrl);
        return pushUrl;
    }

    /**
     * 根据流名称创建播流url
     * @param streamName 视频直播根据流名称（StreamName）而不是根据应用名称（AppName）来判断直播流是否唯一
     * @param playBackType 播放类型 1.rtmp 2.flv 3.m3u8
     * @param endTime 直播间结束时间
     * @param aliLive 阿里云直播配置
     * @return 推流域名+AppName（应用）+StreamName（直播流）+鉴权串
     */
    public static String getPullUrl(String streamName, Integer playBackType, Date endTime, AliLive aliLive) {
        if (Objects.isNull(streamName) || StrUtil.isBlank(streamName)) {
            throw new YamiShopBindException("Stream name cannot be null");
        }
        // 播流域名
        String pullDomain = aliLive.getPullDomain();
        // 应用名称
        String appName = aliLive.getAppName();
        // 播流鉴权key
        String pullAuthKey = aliLive.getPullAuthKey();
        // 过期时间
        String exp = String.valueOf(endTime.getTime() / 1000);
        // 通用播流域名 {pullDomain}/{appName}/{streamName}
        String pullPrefix = StrUtil.format("{}/{}/{}", pullDomain, appName, streamName);
        // 组合md5加密串 /{appName}/{streamName}-{exp}-0-0-{pullAuthKey}
        String md5Url = "";
        if (Objects.equals(playBackType, PlayBackType.RTMP.value())) {
            md5Url = StrUtil.format("/{}/{}-{}-0-0-{}", appName, streamName, exp, pullAuthKey);
        } else if (Objects.equals(playBackType, PlayBackType.FLV.value())) {
            md5Url = StrUtil.format("/{}/{}.flv-{}-0-0-{}", appName, streamName, exp, pullAuthKey);
        } else if (Objects.equals(playBackType, PlayBackType.M3U8.value())) {
            md5Url = StrUtil.format("/{}/{}.m3u8-{}-0-0-{}", appName, streamName, exp, pullAuthKey);
        }
        // md5加密
        String md5Hex = DigestUtil.md5Hex(md5Url);
        // 播流路径
        String pullUrl = "";
        boolean isHttps = Objects.nonNull(aliLive.getIsHttps()) && Objects.equals(aliLive.getIsHttps(), 1);
        if (Objects.equals(playBackType, PlayBackType.RTMP.value())) {
            pullUrl = StrUtil.format("rtmp://{}?auth_key={}-0-0-{}", pullPrefix, exp, md5Hex);
        } else if (Objects.equals(playBackType, PlayBackType.FLV.value())) {
            pullUrl = StrUtil.format(isHttps ? "https://{}.flv?auth_key={}-0-0-{}" : "http://{}.flv?auth_key={}-0-0-{}", pullPrefix, exp, md5Hex);
        } else if (Objects.equals(playBackType, PlayBackType.M3U8.value())) {
            pullUrl = StrUtil.format(isHttps ? "https://{}.m3u8?auth_key={}-0-0-{}" : "http://{}.m3u8?auth_key={}-0-0-{}", pullPrefix, exp, md5Hex);
        }
        logger.info("播流路径为：" + pullUrl);
        return pullUrl;
    }
}
